<template>
	<view class="reservation-info">
		<view class="form">
			<view class="form-item">
				<view class="label">可选时间</view>
				<view class="content">
					<picker mode="date" :start="pickerStartTime" :end="pickerEndTime" :value="formattedCurrentDate"
						@change="onDateChange" fields="day" style="width: 100%;">
						<view class="select-wrapper">
							<view class="select">
								<view class="select-value">{{ selectYear || "--" }}年</view>
								<view class="icon-select">
									<image class="icon" src="@/img/yangcan/ic-arrow-bottom.png"></image>
								</view>
							</view>
							<view style="width: 9rpx;"></view>
							<view class="select">
								<view class="select-value">{{ selectMonth || "--" }}月</view>
								<view class="icon-select">
									<image class="icon" src="@/img/yangcan/ic-arrow-bottom.png"></image>
								</view>
							</view>
							<view style="width: 9rpx;"></view>
							<view class="select">
								<view class="select-value">{{ selectDate || "--" }}日</view>
								<view class="icon-select">
									<image class="icon" src="@/img/yangcan/ic-arrow-bottom.png"></image>
								</view>
							</view>
						</view>
					</picker>
				</view>
			</view>
			<view class="form-item">
				<view class="label">可约地址</view>
				<view class="content">
					<picker style="width: 100%;" :range="getList(centerList)" :value="centerIndex"
						@change="onSelectConfirm($event, 3)">
						<view class="select-wrapper">
							<view class="select">
								<view class="select-value">{{ getCenter || "--" }}</view>
								<view class="icon-select">
									<image class="icon" src="@/img/yangcan/ic-arrow-bottom.png"></image>
								</view>
							</view>
						</view>
					</picker>
				</view>
			</view>
			<view class="form-item">
				<view class="label">可约项目</view>
				<view class="content">
					<picker style="width: 100%;" :range="getList(projectList)" :value="projectIndex"
						@change="onSelectConfirm($event, 4)">
						<view class="select-wrapper">
							<view class="select">
								<view class="select-value">{{ getProject || "--" }}</view>
								<view class="icon-select">
									<image class="icon" src="@/img/yangcan/ic-arrow-bottom.png"></image>
								</view>
							</view>
						</view>
					</picker>
					<view class="tip">备注：体验时长为：60分钟</view>
				</view>
			</view>
			<view v-if="projectIndex != -1" class="form-item">
				<view class="label">体验人数</view>
				<view class="content">
					<picker style="width: 100%;" :range="getList(numberList)" :value="numberIndex"
						@change="onSelectConfirm($event, 5)">
						<view class="select-wrapper">
							<view class="select">
								<view class="select-value">{{ getNumber || "--" }}</view>
								<view class="icon-select">
									<image class="icon" src="@/img/yangcan/ic-arrow-bottom.png"></image>
								</view>
							</view>
						</view>
					</picker>
				</view>
			</view>
			<view v-if="projectIndex != -1" class="form-item">
				<view class="title">
					<view class="title-main">预约时间</view>
					<view class="title-tip">{{ getTimeRange }}</view>
				</view>
				<view class="content">
					<view class="time-wrapper">
						<block v-for="(item, index) in timeList" :key="index">
							<view v-if="index < (timeList.length - 2)" class="time-item"
								:class="{'time-item-disable': item.disable || item.isOverFull || item.isFull, 'time-item-selected': item.selected}"
								@click="onTimeChange(index)">
								{{ item.isFull ? '已约满' : item.label }}
							</view>
						</block>
					</view>
					<view class="tip" style="margin-top: -20rpx;">备注：需要提前：3小时</view>
				</view>
			</view>
		</view>
		<view class="btn" @click="onReservation">确定预约</view>

		<ReservationPopup title="提示" content="预约成功!" type="text" :show="isShow" @updateShow="e => isShow = e"
			@confirm="onConfirm" />
	</view>
</template>

<script>
	import ReservationPopup from '@/components/reservation-popup/index.vue';
	import * as ReservationApi from '@/api/reservation/index.js';
	import {
		showInfo
	} from '@/utils/ToastUtils';
	import StorageUtils from '@/utils/StorageUtils';
	import CacheConfig from '@/config/CacheConfig';

	export default {
		data() {
			return {
				currentYear: "",
				currentMonth: "",
				currentDate: "",
				currentHour: "",
				currentMin: "",

				yearList: [],
				selectYear: "",
				yearIndex: 0,

				monthList: [],
				selectMonth: "",
				monthIndex: 0,

				dateList: [],
				selectDate: "",
				dateIndex: 0,

				pickerStartTime: "",
				pickerEndTime: "",
				currentSelectTime: "",

				centerList: [],
				centerIndex: 0,

				projectList: [],
				projectIndex: 0,

				numberList: [],
				numberIndex: 0,

				timeList: [],

				// 使用次数
				remainCount: 0,

				// 体验时间
				period: 60,

				isShow: false,
			}
		},
		components: {
			ReservationPopup
		},
		onLoad(options) {
			console.log("options", options);
			this.initList(options.date);
		},
		computed: {
			formattedCurrentDate() {
				const year = this.selectYear;
				const month = this.selectMonth;
				const date = this.selectDate;
				return `${year}-${month}-${date}`;
			},
			getCenter() {
				if (this.centerList[this.centerIndex]) {
					return this.centerList[this.centerIndex].label;
				} else {
					return "";
				}
			},
			getProject() {
				if (this.projectList[this.projectIndex]) {
					return this.projectList[this.projectIndex].label;
				} else {
					return "";
				}
			},
			getNumber() {
				if (this.numberList[this.numberIndex]) {
					return this.numberList[this.numberIndex].label;
				} else {
					return "";
				}
			},
			getTimeRange() {
				let startTime = "";
				let endTime = "";
				this.timeList.forEach(v => {
					if (v.selected) {
						startTime = v.label;
					}
				});
				if (startTime) {
					const arr = startTime.split(":");
					endTime = `${(Number(arr[0]) + 1).toString().padStart(2, '0')}:${arr[1]}`
					return `${startTime}-${endTime}`;
				}
				return '';
			}
		},
		methods: {
			initList(selectInfo) {
				const today = new Date();
				const year = today.getFullYear();
				const month = today.getMonth();
				const date = today.getDate();
				this.currentYear = year;
				this.currentMonth = month + 1;
				this.currentDate = date;
				this.currentHour = today.getHours();
				this.currentMin = today.getMinutes();

				this.pickerStartTime = `${this.currentYear}-${this.currentMonth}-${this.currentDate}`;
				const startDate = new Date(this.currentYear, this.currentMonth - 1, this.currentDate);
				startDate.setMonth(startDate.getMonth() + 3);
				this.pickerEndTime = `${startDate.getFullYear()}-${startDate.getMonth() + 1}-${startDate.getDate()}`;;

				if (selectInfo) {
					const arr = selectInfo.split("-");
					this.selectYear = arr[0];
					this.selectMonth = arr[1];
					this.selectDate = arr[2];
				} else {
					this.selectYear = year;
					this.selectMonth = (month + 1).toString().padStart(2, '0');
					this.selectDate = date.toString().padStart(2, '0');
				}
				// this.getYearList();
				// this.getMonthList();
				// this.getDateList();
				this.getCenterList(true);
			},
			// getYearList() {
			// 	const years = [];
			// 	for (let i = this.currentYear; i <= 2100; i++) {
			// 		years.push({
			// 			label: `${i}年`,
			// 			value: i,
			// 		})
			// 	}
			// 	this.yearList = years;
			// },
			// getMonthList() {
			// 	const currentDate = new Date();
			// 	let startMonth = 1;
			// 	if (this.currentYear == this.selectYear) {
			// 		startMonth = Number(this.currentMonth);
			// 	}
			// 	const months = [];
			// 	for (let i = startMonth; i <= 12; i++) {
			// 		months.push({
			// 			label: `${i.toString().padStart(2, '0')}月`,
			// 			value: i,
			// 		})
			// 	}
			// 	this.monthList = months;
			// },
			// getDateList() {
			// 	const currentDate = new Date();
			// 	let startDay = 1;
			// 	if (this.currentYear == this.selectYear && this.currentMonth == this.selectMonth) {
			// 		startDay = this.currentDate;
			// 	}
			// 	const lastDay = new Date(this.selectYear, this.selectMonth, 0);
			// 	const daysInMonth = lastDay.getDate();
			// 	const dates = [];
			// 	for (let day = startDay; day <= daysInMonth; day++) {
			// 		dates.push(String(day).padStart(2, '0'));
			// 	}
			// 	this.dateList = dates.map(v => {
			// 		return {
			// 			label: `${v}号`,
			// 			value: Number(v),
			// 		}
			// 	})
			// },
			getCenterList(isInit = false) {
				ReservationApi.getReservationCenterList().then(res => {
					console.log("getReservationCenterList res", res);
					if (!!res.obj) {
						this.centerList = res.obj.map((v, i) => {
							return {
								label: v.name,
								value: v.id,
								extra: {
									i,
								},
							}
						})
						if (isInit) {
							this.centerIndex = 0;
							this.getCenterInfo();
						}
					}
				})
			},
			getCenterInfo() {
				const param = {
					centerId: this.centerList[this.centerIndex].value,
					year: this.selectYear,
					month: this.selectMonth,
					day: this.selectDate,
				};
				ReservationApi.getReservationCenterInfo(param).then(res => {
					console.log("getReservationCenterInfo res", res.obj.records);
					if (!!res.obj && !!res.obj.records) {
						this.projectList = res.obj.records.map((v, i) => {
							console.log("center", v.center);
							return {
								label: v.itemName,
								value: v.id,
								extra: {
									i,
									openCount: v.openCount,
									openTime: v.openTime,
									times: v.times,
									period: v.period,
									itemTypeId: v.itemType.id
								}
							}
						})
						this.projectIndex = 0;
						// this.period = this.projectList[this.projectIndex].extra.period;
						const [startTime, endTime] = this.projectList[this.projectIndex].extra.openTime.split("-");
						console.log("startTime", startTime);
						console.log("endTime", endTime);
						this.getProjectType(this.projectList[this.projectIndex].extra.itemTypeId);
						// 获取时间选项
						this.getTimeList(startTime, endTime);
						this.getNumberList(this.projectList[this.projectIndex]);
					}
				})
			},
			getList(list) {
				return list.map(v => v.label);
			},
			getTimeList(startTime, endTime) {
				let [startHour, startMin] = startTime.split(":");
				let [endHour, endMin] = endTime.split(":");
				startHour = Number(startHour);
				startMin = Number(startMin);
				endHour = Number(endHour);
				endMin = Number(endMin);
				
				if (startMin < 30 && startMin > 0) {
					startMin = 30;
				} else if (startMin > 30) {
					startMin = 0;
					startHour += 1;
				}
				if (endMin < 30) {
					endMin = 0;
				} else if (endMin > 30){
					endMin = 30;
				}

				let maxHour = startHour;
				let maxMin = 0;
				if (this.selectYear == this.currentYear && this.selectMonth == this.currentMonth && this.selectDate == this
					.currentDate) {
					maxHour = Number(this.currentHour) + 3;
					maxMin = Number(this.currentMin);
					// maxHour = Number(this.currentHour);
					// maxMin = Number(this.currentMin);
				}
				
				let currentHour = startHour;
				let currentMin = startMin;
				const intervals = [];
				// 生成时间间隔（每30分钟一个）
				while (currentHour < endHour || (currentHour === endHour && currentMin <= endMin)) {
					// 检查是否超过结束时间
					if (currentHour > endHour || (currentHour === endHour && currentMin > endMin)) {
						break;
					}

					// 判断是否禁用（早于最大可选择时间）
					const isDisabled = currentHour < maxHour || (currentHour === maxHour && currentMin < maxMin);
				
					// 添加时间选项
					intervals.push({
						label: `${currentHour.toString().padStart(2, '0')}:${currentMin.toString().padStart(2, '0')}`,
						selected: false,
						isFull: false,
						isOverFull: false,
						disable: isDisabled
					});
				
					// 下一个时间点（30分钟后）
					currentMin += 30;
					if (currentMin >= 60) {
						currentMin = 0;
						currentHour += 1;
					}
				}
				this.timeList = intervals;
			},
			getNumberList(val) {
				const numberToChinese = {
					1: '单',
					2: '双',
					3: '三',
					4: '四',
					5: '五',
					6: '六',
				};
				const projectInfo = JSON.parse(JSON.stringify(val));
				console.log("projectInfo", projectInfo);
				this.getProjectType(projectInfo.extra.itemTypeId);
				this.numberList = [];
				for (var i = 1; i <= projectInfo.extra.openCount; i++) {
					this.numberList.push({
						label: `${numberToChinese[i]}人`,
						value: i,
					})
				}
				this.numberIndex = 0;
				this.getTimeCount(1);
			},
			getTimeCount(value) {
				const {
					times,
					openCount
				} = this.projectList[this.projectIndex].extra;
				// console.log("times", times);
				const userInfo = StorageUtils.get(CacheConfig.USER_INFO_KEY);
				this.timeList.forEach((item, index) => {
					item.selected = false;
					item.isOverFull = false;
					item.isFull = false;
				})
				this.timeList.forEach((item, index) => {
					const {
						count = 0,
					} = times.find(v => v.time == item.label) || {};
					// console.log("count", count);
					// console.log("(Number(count) + Number(value))", (Number(count) + Number(value)), openCount);
					if (item.isOverFull || item.isFull) {
						return;
					}
					if (Number(count) == openCount) {
						item.isFull = true;
						if (index < this.timeList.length - 1) {
							this.timeList[index + 1].isFull = true;
						}
					} else if ((Number(count) + Number(value)) > openCount) {
						item.isOverFull = true;
						if (index < this.timeList.length - 1) {
							this.timeList[index + 1].isOverFull = true;
						}
					}
				})
			},
			getProjectType(typeId) {
				const userInfo = StorageUtils.get(CacheConfig.USER_INFO_KEY);
				const param = {
					itemTypeId: typeId,
					userId: userInfo.id,
					current: 1,
					size: 10
				};
				ReservationApi.getReserveUserInfo(param).then(res => {
					console.log("getReserveUserInfo res", res);
					if (res.obj && res.obj.records && res.obj.records[0]) {
						this.remainCount = res.obj.records[0].remainCount;
					} else {
						this.remainCount = 0;
					}
				})
			},
			onDateChange(e) {
				console.log("onDateChange", e);
				const selectInfo = e.target.value;
				const arr = selectInfo.split("-");
				this.selectYear = arr[0];
				this.selectMonth = arr[1];
				this.selectDate = arr[2];
				this.getCenterList(true);
			},
			onSelectConfirm(e, type) {
				console.log("onSelectConfirm", e, type);
				const i = e.detail.value;
				switch (type) {
					case 3:
						if (this.centerIndex == i) return;
						this.centerIndex = i;
						this.getCenterInfo();
						break;
					case 4:
						if (this.projectIndex == i) return;
						this.projectIndex = i;
						console.log("this.projectList[i]", this.projectList[i]);
						// this.period = this.projectList[i].extra.period;
						const [startTime, endTime] = this.projectList[i].extra.openTime.split("-");
						this.getTimeList(startTime, endTime);
						this.getNumberList(this.projectList[i]);
						break;
					case 5:
						if (this.numberIndex == i) return;
						this.numberIndex = i;
						this.getTimeCount(this.numberList[i].value);
						break;
				}
			},
			onTimeChange(index) {
				if (this.timeList[index].disable || this.timeList[index].isFull || this.timeList[index].isOverFull) {
					return;
				}
				if (index >= this.timeList.length - 1 || this.timeList[index + 1].disable || this.timeList[index + 1]
					.isFull || this.timeList[index + 1].isOverFull) {
					showInfo("不足1个小时");
					return;
				}
				const number = this.numberList[this.numberIndex].value;
				console.log("number", number, this.remainCount);
				if (number > this.remainCount) {
					showInfo("请联系管理员添加使用次数");
					return;
				}
				this.timeList.forEach(v => {
					v.selected = false;
				})
				this.timeList[index].selected = true;
				// if (this.timeList[index].selected) {
				// 	this.timeList[index + 1].selected = true;
				// }
			},
			onReservation() {
				if (!this.selectYear) {
					showInfo("请选择预约年份");
					return;
				} else if (!this.selectMonth) {
					showInfo("请选择预约月份");
					return;
				} else if (!this.selectDate) {
					showInfo("请选择预约日期");
					return;
				} else if (!this.getCenter) {
					showInfo("请选择可约地址");
					return;
				} else if (!this.getProject) {
					showInfo("请选择可约项目");
					return;
				} else if (!this.getNumber) {
					showInfo("请选择体验人数");
					return;
				} else if (!this.getTimeRange) {
					showInfo('请选择预约时间');
					return;
				}
				const userInfo = StorageUtils.get(CacheConfig.USER_INFO_KEY);

				const timeArr = this.getTimeRange.split("-");
				const startTime =
					`${this.currentYear}-${this.selectMonth.toString().padStart(2, '0')}-${this.selectDate.toString().padStart(2, '0')} ${timeArr[0]}:00`;
				const endTime =
					`${this.currentYear}-${this.selectMonth.toString().padStart(2, '0')}-${this.selectDate.toString().padStart(2, '0')} ${timeArr[1]}:00`;
				console.log("startTime", startTime);
				console.log("endTime", endTime);

				const param = {
					userId: userInfo.id,
					itemId: this.projectList[this.projectIndex].value,
					reserveCount: this.numberList[this.numberIndex].value,
					startTime,
					endTime,
					reserveState: 1,
					username: userInfo.nickName,
					phone: userInfo.mobile,
				};
				console.log("param", param);
				ReservationApi.saveReservationInfo(param).then(res => {
					this.isShow = true;
				})
			},
			onConfirm() {
				this.isShow = false;
				uni.navigateBack();
			}
		}
	}
</script>

<style lang="scss">
	.reservation-info {
		min-height: 100vh;
		background-color: #fff;
		padding: 32rpx 0;
		font-family: PingFang;
	}

	.form {
		padding: 25rpx;

		.form-item {
			margin-bottom: 45rpx;

			.label {
				font-size: 35rpx;
				color: #000;
				font-weight: bold;
				margin-bottom: 24rpx;
			}

			.title {
				display: flex;
				align-items: flex-end;
				margin-bottom: 24rpx;

				.title-main {
					font-size: 35rpx;
					color: #000;
					font-weight: bold;
				}

				.title-tip {
					flex: 1;
					text-align: right;
					margin-right: 20rpx;
					color: #ff8d25;
					font-size: 30rpx;
				}
			}

			.content {
				display: flex;
				flex-direction: column;
				align-items: flex-start;

				.select-wrapper {
					width: 100%;
					display: flex;
					align-items: center;

					.select {
						flex: 1;
						height: 107rpx;
						border: 1rpx solid #b7b7b7;
						border-radius: 20rpx;
						display: flex;
						align-items: center;
						background-color: #f5f5f5;

						.select-value {
							flex: 1;
							margin-left: 25rpx;
							font-size: 33rpx;
							font-weight: bold;
							color: #717171;
						}

						.icon-select {
							margin-top: 10rpx;
							margin-right: 10rpx;
							padding: 20rpx;

							.icon {
								width: 38rpx;
								height: 23rpx;
							}
						}
					}
				}

				.radio-wrapper {
					width: 100%;
					display: flex;
					align-items: center;
					justify-content: space-between;

					.radio-item {
						width: 190rpx;
						height: 92rpx;
						background-color: #f5f5f5;
						display: flex;
						align-items: center;
						justify-content: center;
						border: 1rpx solid #b7b7b7;
						border-radius: 20rpx;
						font-size: 30rpx;
						font-weight: bold;
						color: #7e7e7e;
					}

					.radio-item-selected {
						background-color: #ffeee5 !important;
						border-color: #ff7b09 !important;
						color: #ff7b09;
					}
				}

				.time-wrapper {
					display: flex;
					flex-wrap: wrap;

					.time-item {
						width: 168rpx;
						height: 79rpx;
						border: 1rpx solid #c4c4c4;
						border-radius: 20rpx;
						font-size: 30rpx;
						font-weight: bold;
						color: #717171;
						display: flex;
						align-items: center;
						justify-content: center;
						margin-right: 9rpx;
						margin-bottom: 35rpx;
					}

					.time-item-disable {
						background-color: #f5f5f5;
						border-color: #f5f5f5;
						color: #cccccc;
					}

					.time-item-selected {
						background-color: #ffeee5;
						border-color: #ff7e00;
						color: #ff7e00;
					}

					.time-item:nth-of-type(4n) {
						margin-right: 0;
					}
				}

				.tip {
					height: 35rpx;
					padding: 0 20rpx;
					background-color: #fff0e2;
					border-radius: 10rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					color: #ff8d25;
					font-size: 22rpx;
					margin-top: 15rpx;
				}
			}
		}
	}

	.btn {
		width: 276rpx;
		height: 99rpx;
		border-radius: 30rpx;
		background-color: #ff7a19;
		font-size: 38rpx;
		font-weight: bold;
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto;
	}

	.btn-disable {}
</style>